'use strict';
const db = uniCloud.database();
const lunch_hour = 8
const lunch_minute = 40
const dinner = 11
const next = 18

function convertUTCToBeijingDate(utcDate) {
  // 创建一个新的 Date 对象，解析传入的 UTC 时间
  let date = new Date(utcDate);
  // 获取北京的时区偏移（东8区）
  date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
  date.setHours(date.getHours() + 8);
  // 格式化日期为本地时间
  return new Date(date);
} 

function padZero(num) {
  return num < 10 ? `0${num}` : `${num}`;
}

// 处理当日报餐
async function handleTodayMeal(data) {

  const now =new Date();
  //转为北京时间 
  var beijingDate=convertUTCToBeijingDate(now);
  const hours = padZero(beijingDate.getHours());
  const minutes = padZero(beijingDate.getMinutes());
  const seconds = padZero(beijingDate.getSeconds());
  // 打印当前时间
  // console.log(beijingTime)
  console.log(`.。。。。。。。。。。。。。。。北京时间：${hours}:${minutes}:${seconds}`);

  // 时间戳
  const createTime = now.getTime();
  // 打印当前时间
  console.log('-------------'+createTime)
  // 查询是否存在当天的报餐记录
  const todayStart = new Date(beijingDate);
  todayStart.setHours(0, 0, 0, 0);
  const todayEnd = new Date(beijingDate);
  todayEnd.setHours(23, 59, 59, 999);

  const queryRes = await db.collection('canteen')
    .where({
      name: data.name,
      department: data.department,
      createTime: db.command.gte(todayStart.getTime()).and(db.command.lte(todayEnd.getTime()))
    })
    .get();
  console.log('处理当日报餐业务');
  let isUpdate = false;
  let previousMeal = null;

  if (queryRes.data.length > 0) {
    console.log('更新操作');
    // 如果存在，获取之前的报餐记录
    previousMeal = queryRes.data[0];
    // 判断是否超过午餐报餐时间
    if (hours > lunch_hour || (hours === lunch_hour && minutes > lunch_minute)) {
      console.log('只更新晚餐');
      // 如果超过午餐报餐时间，只更新晚餐 >8:40
      if(hour < dinner){
        const updateRes = await db.collection('canteen')
          .doc(previousMeal._id)
          .update({
            lunch: previousMeal.lunch,
            dinner: data.dinner,
            createTime: createTime
          });
        }else{
          // >11:00
          return {
            code: 1,
            message: '报餐时间不合法',
            isUpdate: isUpdate
          };
        }
    } else {
      console.log('更新中餐和晚餐');
      // 如果未超过午餐报餐时间，更新中餐和晚餐 8:40<
      const updateRes = await db.collection('canteen')
        .doc(previousMeal._id)
        .update({
          lunch: data.lunch,
          dinner: data.dinner,
          createTime: createTime
        });
    }
    isUpdate = true;
  } else {
    // 如果不存在，新增记录
    const addRes = await db.collection('canteen').add({
      ...data,
      createTime: createTime
    });
  }

  return {
    code: 0,
    message: '当日报餐成功',
    isUpdate: isUpdate
  };
}

// 处理次日报餐
async function handleNextDayMeal(data) {
  const now =new Date();
  //转为北京时间 
  var beijingDate=convertUTCToBeijingDate(now);
  const hours = padZero(beijingDate.getHours());
  const minutes = padZero(beijingDate.getMinutes());
  const seconds = padZero(beijingDate.getSeconds());
  // 打印当前时间
  // console.log(beijingTime)
  console.log(`.。。。。。。。。。。。。。。。北京时间：${hours}:${minutes}:${seconds}`);
  
  const tomorrow = new Date(beijingDate);
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 1, 0, 0); // 第二天的00:01
  const createTime = tomorrow.getTime();
  console.log('处理次日报餐业务');	
  // 查询是否存在次日的报餐记录
  const queryRes = await db.collection('canteen')
    .where({
      name: data.name,
      department: data.department,
      createTime: db.command.gte(createTime)
    })
    .get();

  let isUpdate = false;
  let previousMeal = null;
  if (queryRes.data.length > 0) {
    // 如果存在，获取之前的报餐记录
    previousMeal = queryRes.data[0];
    // 更新记录
    const updateRes = await db.collection('canteen')
      .doc(previousMeal._id)
      .update({
        lunch: data.lunch,
        dinner: data.dinner,
        createTime: createTime
      });
    isUpdate = true;
  } else {
    // 如果不存在，新增记录
    const addRes = await db.collection('canteen').add({
      ...data,
      createTime: createTime
    });
  }

  return {
    code: 0,
    message: '次日报餐成功',
    isUpdate: isUpdate
  };
}

// 处理取消当日报餐
async function handleCancelTodayMeal(data) {
	const now =new Date();
	//转为北京时间 
	var beijingDate=convertUTCToBeijingDate(now);
	const hours = padZero(beijingDate.getHours());
	const minutes = padZero(beijingDate.getMinutes());
	const seconds = padZero(beijingDate.getSeconds());
	// 打印当前时间
	// console.log(beijingTime)
	console.log(`.。。。。。。。。。。。。。。。北京时间：${hours}:${minutes}:${seconds}`);
	
	// 时间戳
	const createTime = now.getTime();
	// 打印当前时间
	console.log('-------------'+createTime)
	

  // 打印当前时间
  console.log(`北京时间：${hours}:${minutes}:${seconds}`);

  // 查询是否存在当天的报餐记录
  const todayStart = new Date(beijingDate);
  todayStart.setHours(0, 0, 0, 0);
  const todayEnd = new Date(beijingDate);
  todayEnd.setHours(23, 59, 59, 999);

  const queryRes = await db.collection('canteen')
    .where({
      name: data.name,
      department: data.department,
      createTime: db.command.gte(todayStart.getTime()).and(db.command.lte(todayEnd.getTime()))
    })
    .get();
  console.log('处理取消业务');

  if (queryRes.data.length > 0) {
    // 如果存在，更新记录，将中餐和晚餐字段改为 false
    if (hours > lunch_hour || (hours === lunch_hour && minutes > lunch_minute)) {
      console.log('31');
      if(hours > next){
        const updateRes = await db.collection('canteen')
        .doc(queryRes.data[0]._id)
        .update({
          dinner: false
        });
      }else{
        return {
          code: 1,
          message: '不在合法报餐时间'
        };
      }
      
    } else {
      console.log('32');
      const updateRes = await db.collection('canteen')
        .doc(queryRes.data[0]._id)
        .update({
          lunch: false,
          dinner: false
        });
    }
    return {
      code: 0,
      message: '当日取消报餐成功'
    };
  } else {
    return {
      code: 404,
      message: '未找到当日报餐记录'
    };
  }
}

// 处理取消次日报餐
async function handleCancelNextDayMeal(data) {
  const now =new Date();
  //转为北京时间 
  var beijingDate=convertUTCToBeijingDate(now);
  const hours = padZero(beijingDate.getHours());
  const minutes = padZero(beijingDate.getMinutes());
  const seconds = padZero(beijingDate.getSeconds());
  // 打印当前时间
  // console.log(beijingTime)
  console.log(`.。。。。。。。。。。。。。。。北京时间：${hours}:${minutes}:${seconds}`);
  
  
  const tomorrow = new Date(beijingDate);
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 1, 0, 0); // 第二天的00:01
  const createTime = tomorrow.getTime();

  // 查询是否存在次日的报餐记录
  const queryRes = await db.collection('canteen')
    .where({
      name: data.name,
      department: data.department,
      createTime: db.command.gte(createTime)
    })
    .get();

  if (queryRes.data.length > 0) {
    // 如果存在，更新记录，将中餐和晚餐字段改为 false
    const updateRes = await db.collection('canteen')
      .doc(queryRes.data[0]._id)
      .update({
        lunch: false,
        dinner: false
      });

    return {
      code: 0,
      message: '次日取消报餐成功'
    };
  } else {
    return {
      code: 404,
      message: '未找到次日报餐记录'
    };
  }
}

exports.main = async (event, context) => {
  const { action, data } = event;

  try {
    switch (action) {
      case 'submitTodayMeal':
        return await handleTodayMeal(data);
      case 'submitNextDayMeal':
        return await handleNextDayMeal(data);
      case 'cancelTodayMeal':
        return await handleCancelTodayMeal(data);
      case 'cancelNextDayMeal':
        return await handleCancelNextDayMeal(data);
      default:
        return {
          code: 400,
          message: '未知操作'
        };
    }
  } catch (err) {
    return {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    };
  }
}; 